package com.yj.event_listener.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.Telephony;
import android.util.Log;

import androidx.annotation.RequiresApi;

public class SmsUtil {


    public static Cursor getFirstSMSMessage(Context context) {
        // Define the content URI for SMS messages
        Uri uri = Telephony.Sms.Inbox.CONTENT_URI;

        // Define the projection (columns to retrieve)
        String[] projection = new String[0];
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            projection = new String[]{
                    Telephony.Sms.THREAD_ID,
                    Telephony.Sms.ADDRESS,
                    Telephony.Sms.BODY,
                    Telephony.Sms.DATE,
                    Telephony.Sms.CREATOR,
            };
        }

        // Define the sort order (order by date in ascending order to get the oldest message)
//        String sortOrder = Telephony.Sms.DATE + " DESC";

        // Perform the query
        ContentResolver contentResolver = context.getContentResolver();
        Bundle bundle = new Bundle();
        bundle.putInt(ContentResolver.QUERY_ARG_LIMIT, 1);
        bundle.putStringArray(ContentResolver.QUERY_ARG_SORT_COLUMNS, new String[]{Telephony.Sms.DATE});
        bundle.putInt(ContentResolver.QUERY_ARG_SORT_DIRECTION, ContentResolver.QUERY_SORT_DIRECTION_DESCENDING);
        Cursor cursor = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            cursor = contentResolver.query(uri, projection, bundle, null);
        }

        return cursor;
    }

}
